package com.zero.guava.samples.CollectionsDemo;


import com.google.common.collect.*;

import java.util.HashMap;

/**
 * 提供一些线程安全的类来避免并发引起的资源竞争问题，Guava为我们提供了Immutable collections，不可变集合，
 * 它是线程安全的。List、Set、Map这些常用的集合类型，Guava都为我们提供了相应的不可变集合类，
 * 分别 是：ImmutableList、ImmutableSet、ImmutableMap
 */
public class ImmutableCollectionsTest {

    public static void main(String[] args) {
        testImmutableCollections();
    }


    public static void testImmutableCollections() {

        //builder模式创建不可变Set集合
        ImmutableSet<String> immutableSetByBuilder = ImmutableSet
                .<String>builder().add("First")
                .addAll(Lists.asList("Second", new String[]{"Third"}))
                .build();
        System.out.println(immutableSetByBuilder);

        //of方法创建不可变Set集合
        ImmutableSet<String> immutableSetByOf = ImmutableSet
                .<String>of("First", "Second", "Third");
        System.out.println(immutableSetByOf);

        //copyOf方法创建不可变Set集合
        ImmutableSet<String> immutableSetByCopyOf = ImmutableSet
                .<String>copyOf(new String[]{"First", "Second", "Third"});

        //builder模式创建不可变List集合
        ImmutableList<String> immutableListByBuilder = ImmutableList
                .<String>builder().add("First")
                .addAll(Lists.asList("Second", new String[]{"Third"}))
                .build();

        //of方法创建不可变List集合
        ImmutableList<String> immutableListByOf = ImmutableList
                .<String>of("First", "Second", "Third");

        //copyOf方法创建不可变List集合
        ImmutableList<String> immutableListByCopyOf = ImmutableList
                .<String>copyOf(new String[]{"First", "Second", "Third"});

        //builder模式创建不可变Map集合
        ImmutableMap<String, String> immutableMapByBuilder = ImmutableMap
                .<String, String>builder().put("First", "1")
                .putAll(new HashMap<String, String>() {
                    {
                        put("Second", "2");
                        put("Third", "3");
                    }
                }).build();

        //of方法创建不可变Map集合
        ImmutableMap<String, String> immutableMapByOf = ImmutableMap
                .<String, String>of("First", "1", "Second", "2", "Third", "3");
        //copyOf方法创建不可变Map集合
        ImmutableMap<String, String> immutableMapByCopyOf = ImmutableMap
                .<String, String>copyOf(new HashMap<String, String>() {
                    {
                        put("First", "1");
                        put("Second", "2");
                        put("Third", "3");
                    }
                });

    }
}
